<template>
  <view class="">
    <navBar :title="props.processDesc"></navBar>
    <subtitle titleText="派工单信息"></subtitle>
    <dispatchOrderInformation
      :proTaskList="proTaskList"
    ></dispatchOrderInformation>
    <view class="w-100% h-16rpx" style="background-color: #eeeeee"></view>
    <subtitle titleText="检验项目"></subtitle>
    <view class="mt-24rpx mr-32rpx ml-32rpx">
      <u-table>
        <u-tr class="u-tr">
          <u-th class="u-th">
            <view class="flex-wrap-left w-299rpx ml-18rpx"> 检查项目 </view>
          </u-th>
          <u-th class="u-th">
            <view class="flex-wrap-right w-299rpx mr-18rpx"> 检验结果 </view>
          </u-th>
        </u-tr>
        <u-tr class="u-tr" v-for="(item, index) in inspectionList" :key="index">
          <u-td class="u-td">
            <view class="tabListText flex-wrap-left w-299rpx ml-18rpx">
              {{ item.checkItem }}
            </view>
          </u-td>
          <u-td class="u-td" v-if="item.checkType === 3">
            <view class="flex-space-between pl-32rpx pr-32rpx">
              <view class="tabListText"> NO </view>
              <u-switch
                inactiveColor="#FB2525"
                activeColor="#36C659"
                v-model="item.checkResult"
              ></u-switch>
              <view class="tabListText"> OK </view>
            </view>
          </u-td>
          <u-td class="u-td" v-else>
            <view class="flex-wrap-right pl-32rpx pr-32rpx">
              <u-field
                v-model="item.checkText"
                :label-width="0"
                placeholder=""
                :border-bottom="false"
                input-align="right"
                @blur="losefocusBlur(item.checkText, index)"
              />
            </view>
          </u-td>
        </u-tr>
      </u-table>
    </view>
    <view class="w-100% h-144rpx"></view>
    <view class="suctionbottom">
      <view class="no button" @click="closeover"> 不合格 </view>
      <u-button
        type="primary"
        :loading="loadingEligible"
        class="button"
        @click="qualified"
      >
        合格
      </u-button>
    </view>
    <u-popup
      v-model="show"
      mode="bottom"
      height="1110rpx"
      :mask-close-able="false"
      @close="closePopup"
    >
      <subtitle
        titleText="不良原因明细"
        closeicon
        @closeover="closeover"
      ></subtitle>
      <scroll-view
        :scroll-into-view="'textarea' + remarkgo"
        scroll-with-animation
        scroll-y
        style="height: 1020rpx"
      >
        <multiLevelCheckBox
          :unqualifiedList="unqualifiedList"
          @unqualifiedSubmissionList="unqualifiedSubmissionList"
        >
        </multiLevelCheckBox>
        <view class="ml-32rpx mr-32rpx mb-32rpx mt-8rpx">
          <view class="mb-32rpx">
            <span class="uploadspan1">上传图片</span>
            <span class="uploadspan2">（最多上传6张）</span>
          </view>
          <uploadImg
            ref="uUpload1"
            :id="id"
            :dataimg="dataimg"
            @imageNum="imageNum"
          ></uploadImg>
        </view>
        <view class="">
          <subtitle titleText="检测数量"></subtitle>
          <view class="flex-space-between">
            <view class="mt-35rpx ml-32rpx jiancetext"> 不合格数量（米） </view>
            <view class="mt-35rpx mr-32rpx">
              <u-number-box
                bg-color="#FFFFFF"
                v-model="checkQuantity"
              ></u-number-box>
            </view>
          </view>
        </view>
        <view
          class="m-32rpx pt-20rpx pr-24rpx pl-28rpx"
          style="border: 1px solid #dddddd"
        >
          <textarea
            class="w-100%"
            placeholder="备注（非必填）"
            @input="descInput"
            name=""
            maxlength="500"
            v-model="textarea"
          ></textarea>
          <view
            class="w-100% h-52rpx textareahint"
            :id="'textarea' + remarkgoid"
          >
            还可以输入 {{ textareaNum }} 字
          </view>
        </view>
        <view class="w-100% h-144rpx"></view>
      </scroll-view>
      <view class="suctionbottom">
        <view
          class="no button2"
          @click="upload"
          :class="imgNumber < 6 ? 'no' : 'no2'"
        >
          拍照上传
        </view>
        <view class="no button2" @click="remarkanchor"> 检验数量 </view>
        <u-button
          type="primary"
          :loading="loadingDisqualification"
          class="button2"
          @click="unqualifiedSubmission"
        >
          提交
        </u-button>
      </view>
    </u-popup>
  </view>
</template>
<script lang="ts" setup>
	import navBar from "@/components/navbar.vue";
	import uploadImg from "@/components/uploadImg/uploadImg.vue";
	import subtitle from "@/components/subtitle.vue";
	import multiLevelCheckBox from "@/components/multiLevelCheckBox.vue";
	import dispatchOrderInformation from "@/components/dispatchOrderInformation.vue";
	import { onReady } from "@dcloudio/uni-app";
	import {
		queryTaskDetail,
		submitQualifiedTaskResult,
		queryAllQualifiedReason,
		submitUnQualifiedReason,
		deleteImage,
	} from "@/common/api/operationApi";
	import { ref, onMounted, onUnmounted, onBeforeUnmount } from "vue";
	const props = defineProps<{
		processDesc ?: string[];
		prodWorkList ?: string | [];
		id ?: string | [];
	}>();

	const loadingEligible = ref<boolean>(false);
	const loadingDisqualification = ref<boolean>(false);

const show = ref<boolean>(false);
const inspectionList = ref<string[]>([]);
const proTaskList = ref<AnyObject>([]);
const unqualifiedList = ref<string[]>([]);
const id = ref<string[]>([]);
const textarea = ref<string>("");

	const prodWorkList = ref<string[]>([]);
	const taskIds = ref<string[]>([]);
	onMounted(() => {
		id.value = props.id;
		let split1 = props.prodWorkList.split(",");
		prodWorkList.value = split1;
		let split2 = props.id.split(",");
		taskIds.value = split2;
		tabList();
	});

	async function tabList() : Promise<void> {
		const data = await queryTaskDetail({
			processDesc: props.processDesc,
			// prodWorkList: prodWorkList.value,
			taskIds: taskIds.value,
			taskType: 12,
		});
		proTaskList.value = data.proTaskList;
		inspectionList.value = data.inspectionList;
	}

	const dataimg = ref<string[]>([]);
	async function closeover() {
		if (checkout()) {
			uni.showToast({
				title: "检查项未填写完成，请补充！",
				icon: "none",
			});
		} else {
			show.value = !show.value;
		}

		// show.value = !show.value
	}

	function checkout() {
		return inspectionList.value.some((item) => {
			return item.checkType !== 3 && item.checkText === "";
		});
	}

// 定义一个变量来存储setTimeout()返回的定时器ID
let timerId: number | null = null;
async function qualified(): Promise<void> {
  loadingEligible.value = true;
  timerId = setTimeout(() => {
    // 延迟执行的代码
    loadingEligible.value = false;
  }, 1000);
  if (checkout()) {
    uni.showToast({
      title: "检查项未填写完成，请补充！",
      icon: "none",
    });
  } else {
    var obj = props.id.split(",");
    const data = await submitQualifiedTaskResult({
      inspectionList: inspectionList.value,
      result: 1,
      taskIds: obj,
    });
    uni.showToast({
      title: data,
      icon: "none",
    });
    // 返回B页面并传递参数
    timerId = setTimeout(() => {
      // 延迟执行的代码
      uni.navigateBack({
        delta: 1,
        success() {
          tabList();
        },
      });
    }, 1000);
  }
}
// 如果需要在组件销毁时清除定时器，可以在组件的beforeUnmount()生命周期钩子中清除定时器
onBeforeUnmount(() => {
  if (timerId) {
    clearTimeout(timerId);
  }
});
onReady(() => {
  disqualificationList();
});
async function disqualificationList(): Promise<void> {
  const data = await queryAllQualifiedReason();
  unqualifiedList.value = data.list;
}

	const imgNumber = ref<number>(0);
	function imageNum(e : number) {
		imgNumber.value = e;
	}
	const uUpload1 = ref(null);
	const upload = () => {
		if (imgNumber.value < 6) {
			uUpload1.value.turnUpTheCamera();
		} else {
			uni.showToast({
				title: "最多只能上传6张图片！",
				icon: "none",
			});
		}
	};

	const textareaNum = ref<number>(500);
	const descInput = () => {
		textareaNum.value = 500 - textarea.value.length;
	};
	const remarkgo = ref<string>("");
	const remarkgoid = ref<string>("no");
	const timer = ref();
	const remarkanchor = () => {
		remarkgo.value = "go";
		remarkgoid.value = "go";
		timer.value = setTimeout(() => {
			remarkgo.value = "";
			remarkgoid.value = "no";
		}, 1500);
	};

const reasonList = ref<string[]>([]);
function unqualifiedSubmissionList(e) {
  reasonList.value = e;
}
const checkQuantity = ref<number>(0);
const Integer = ref<number>(null);
async function unqualifiedSubmission(): Promise<void> {
  loadingDisqualification.value = true;
  let obj = props.id.split(",");
  timerId = setTimeout(() => {
    // 延迟执行的代码
    loadingDisqualification.value = false;
  }, 1000);
  const resultReq = {
    inspectionList: inspectionList.value,
    result: 1,
    taskIds: obj,
  };
  const data = await submitUnQualifiedReason({
    reasonList: reasonList.value,
    resultReq: resultReq,
    remark: textarea.value,
    checkReel: Integer.value === null ? 0 : Integer.value,
    prodWork: proTaskList?.value[0].prodWork,
    workScanNum: proTaskList?.value[0].workScanNum,
    processDesc: proTaskList?.value[0].processDesc,
    checkQuantity: checkQuantity.value,
  });
  uni.showToast({
    title: data,
    icon: "none",
  });
  timerId = setTimeout(() => {
    // 延迟执行的代码
    uni.navigateBack({
      delta: 1,
      success() {
        tabList();
      },
    });
  }, 1000);
}

//失去焦点
const losefocusBlur = (v, i) => {
  if (v === "0") {
    inspectionList.value[i].checkText = "";
    uni.showToast({
      title: " 检查项不能为0 ",
      icon: "none",
    });
    return;
  } else if (v === "1") {
    let obj = JSON.parse(JSON.stringify(inspectionList.value[i].checkText));
    if (inspectionList.value[i].checkText !== "") {
      inspectionList.value[i].checkText = Number(obj).toFixed(2);
    }
  }
};

onUnmounted(() => {
  clearTimeout(timer.value);
  timer.value = "";
});

	onUnmounted(() => {
		clearTimeout(timer.value);
		timer.value = "";
	});

	async function closePopup() {
		let obj = props.id.split(",");
		const data = await deleteImage({
			taskIds: obj,
		});
	}
</script>

<style scoped>
	:v-deep .uni-textarea-placeholder .input-placeholder {
		font-size: 24rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #cacaca;
	}

	.custom-style {
		width: 343rpx;
		height: 88rpx;
		margin: 0rpx !important;
		font-size: 32rpx;
		font-family: PingFangSC-Semibold, PingFang SC;
		font-weight: 600;
	}

	.u-td {
		height: 96rpx;
	}

	.u-th {
		height: 80rpx;
	}

	.tabListText {
		font-size: 26rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #4b4d55;
	}

	.suctionbottom .u-btn {
		margin: 0px;
		margin-left: 0px;
		margin-right: 0px;
	}

	.suctionbottom .button {
		width: 343rpx;
		height: 88rpx;
		border-radius: 4rpx;
		font-size: 32rpx;
		font-family: PingFangSC-Semibold, PingFang SC;
		font-weight: 600;
		line-height: 84rpx;
		text-align: center;
	}

	.suctionbottom .button2 {
		width: 224rpx;
		height: 88rpx;
		border-radius: 4rpx;
		font-size: 32rpx;
		font-family: PingFangSC-Semibold, PingFang SC;
		font-weight: 600;
		line-height: 84rpx;
		text-align: center;
	}

	.suctionbottom .no {
		background: #ffffff;
		border: 1rpx solid #2f7bff;
		color: #2f7bff;
	}

	.suctionbottom .no2 {
		background: #ffffff;
		border: 1rpx solid #99beff;
		color: #99beff;
	}

	.suctionbottom .no:active {
		background: #ffffff;
		border: 1rpx solid #99beff;
		color: #99beff;
	}

	.suctionbottom .yes {
		background: #2f7bff;
		border: 1rpx solid #2f7bff;
		color: #ffffff;
	}

	.suctionbottom .yes:active {
		background: #99beff;
		border: 1rpx solid #99beff;
		color: #ffffff;
	}

	.uploadspan1 {
		font-size: 24rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #1e1f22;
	}

	.uploadspan2 {
		font-size: 24rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #7d7f88;
	}

	.textareahint {
		font-size: 24rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #cacaca;
		line-height: 52rpx;
	}

	::v-deep .u-number-input {
		border-left: 1rpx solid #cacaca;
		border-right: 1rpx solid #cacaca;
		margin: 0;
		height: 100% !important;
		width: 88rpx;
	}

	::v-deep .u-numberbox {
		border: 1rpx solid #cacaca;
		height: 56rpx !important;
		border-radius: 4rpx;
	}

	::v-deep .u-icon-disabled {
		background-color: #ffffff !important;
	}

	.jiancetext {
		font-size: 24rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #1e1f22;
	}

	.u-field {
		padding-left: 0rpx;
		padding-right: 0rpx;
	}

	.u-switch {
		width: 88rpx;
		height: 50rpx;
	}

	::v-deep .u-switch__node {
		width: 38rpx !important;
		height: 38rpx !important;
		margin: 6rpx;
	}
</style>